package com.jl.cloud.terminal.controller;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.dynamic.datasource.annotation.DSTransactional;
import com.jl.cloud.commom.aspect.DistributedLock;
import com.jl.cloud.commom.base.BaseResponse;
import com.jl.cloud.commom.utils.RocketMqUtils;
import com.jl.cloud.terminal.api.dto.TerminalResDto;
import com.jl.cloud.terminal.model.Terminal;
import com.jl.cloud.terminal.service.ConsumersService;
import com.jl.cloud.terminal.service.TerminalService;
import com.jl.cloud.terminal.thread.TestThread;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.apache.seata.spring.annotation.GlobalTransactional;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Executor;

@RestController
@Slf4j
@RefreshScope
public class TerminalController {

    private Integer i = 0;


    @Resource
    private TerminalService terminalService;


    @Resource
    private ConsumersService consumersService;

    @Value("${test}")
    private Integer t;

    @Resource
    TestThread thread;


    @GetMapping("getTerminal")
    public BaseResponse<List<TerminalResDto>> getTerminal() {
        thread.start();
        BaseResponse baseResponse = new BaseResponse();
        baseResponse.setMessage("成功");
        List<TerminalResDto> result = new ArrayList<>();
        log.info("请求进来,控制层{}","11111111111111111111111");
        List<Terminal> all = terminalService.findAll();
        for (Terminal terminal : all) {
            TerminalResDto terminalResDto = new TerminalResDto();
            BeanUtils.copyProperties(terminal, terminalResDto);
            result.add(terminalResDto);
        }
        baseResponse.setResult(result);
        RocketMqUtils.sendMessage("demoTopic","*", JSONObject.toJSONString(result));
        return baseResponse;
    }


    @GetMapping("updateTransaction")
    public BaseResponse updateTransaction() {
        terminalService.updateTransaction();
        BaseResponse baseResponse = new BaseResponse();
        baseResponse.setMessage("成功");
        return baseResponse;
    }


    /**
     * 分布式事务
     * @return
     */
    @GetMapping("overallTransaction")
    //分布式事务
    @GlobalTransactional(rollbackFor = Exception.class)
    public BaseResponse overallTransaction() {
        i++;
        terminalService.overallTransaction(i);
        consumersService.updateTransaction(i);
        if(i % 5 == 0){
            Integer i = null;
            i.toString();
        }
        BaseResponse baseResponse = new BaseResponse();
        baseResponse.setMessage("成功");
        return baseResponse;
    }


}
